<template>
  <p-card :bordered="false" :class="'cust-erp-sub-tab'">
    <!-- 查询区域 -->
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="申请编号">
              <p-input-search
                placeholder="请输入申请编号"
                v-model="queryParam.orderNo"
              ></p-input-search>
            </p-form-item>
          </p-col>
           <p-col :xl="6" :lg="7" :md="8" :sm="24">
              <p-button @click="loadData" type="primary" icon="search">查询</p-button>
              <p-button @click="reloadData" type="primary" icon="reload" style="margin-left:15px">重置</p-button>
           </p-col>
        </p-row>
      </p-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <p-button @click="handleADDApply" type="primary" icon="plus">新增</p-button>
      <p-button @click="submitButton" type="primary" >提交</p-button>
      <!-- 高级查询区域 -->
      <j-super-query
        :fieldList="fieldList"
        ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"
      ></j-super-query>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>

        <span style="float: right">
          <a @click="handleExportXls('特殊人员工时申请')"
            ><p-icon type="download" />导出</a
          >
         
          <p-divider type="vertical" />
          <a @click="loadData()"><p-icon type="sync" />刷新</a>
          <p-divider type="vertical" />
          <p-popover
            title="自定义列"
            trigger="click"
            placement="leftBottom"
            :overlay-style="getWidth"
          >
            <template slot="content">
              <p-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="(item, index) in defColumns">
                    <template
                      v-if="
                        item.key != 'rowIndex' && item.dataIndex != 'action'
                      "
                    >
                      <p-col :span="12"
                        ><p-checkbox :value="item.dataIndex">{{
                          item.title
                        }}</p-checkbox></p-col
                      >
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a><p-icon type="setting" />自定义列</a>
          </p-popover>
        </span>
      </div>

      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :scroll="{x: '100%'}"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          getCheckboxProps,
          columnWidth: 50,
          type: 'checkbox',
        }"
        :customRow="clickThenSelect"
        @change="handleTableChange"
      >
        <span slot="orderNo" slot-scope="text,record">
         <a href="javascript:;" @click="shwoModeal(record)">{{text}}</a>
        </span>

         <span slot="approveStatus" slot-scope="text">
          {{approveStatus[text]}}
        </span>

        <span slot="action" slot-scope="text, record">
          <a v-if="record.approveStatus === '0'" @click="handleEdit(record)">编辑</a>
          <a v-if="record.approveStatus === '0'" @click="handleDeleteItem(record)" class="ml10 red">删除</a>
        </span>


      </p-table>
    </div>

    <mesHrMonthlyEmpDeclare-modal
      ref="modalForm"
      :EnhanceJS="EnhanceJS"
      @ok="modalFormOk"
    ></mesHrMonthlyEmpDeclare-modal>
  </p-card>
</template>

<script>
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import { api } from "@/api/manage";
import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
import { filterObj } from "@/utils/util";
import MesHrMonthlyEmpDeclareModal from "./modules/MesHrMonthlyEmpDeclareModal";
import Vue from "vue";
import {
  initDictOptions,
  filterMultiDictText,
} from "@/components/dict/JDictSelectUtil";
import ButtonExpHandler from "@/components/jeecgbiz/modules/ButtonExpHandler";
import { postAction, getAction, deleteAction } from "@/api/manage";
import FxCompontensModal from "@/components/jeecgbiz/FxCompontensModal";
import moment from "moment";

//高级查询modal需要参数
const superQueryFieldList = [
  {
    value: "applyNo",
    text: "申请编号",
    type: "orderNo",
  },
  {
    value: "declareDate",
    text: "申报日期",
    type: "Date",
  },
  {
    value: "declareWorkroom",
    text: "申报车间",
    type: "String",
  },
  {
    value: "approveStatus",
    text: "审批状态",
    type: "select",
    dictCode: "mes_hr_monthly_approve_status",
  },
  {
    value: "shiftName",
    text: "班次",
    type: "select",
  },
  {
    value: "declareClassname",
    text: "班组",
    type: "select",
  },
  {
    value: "linename",
    text: "线体",
    type: "select",
  },
  {
    value: "productionNo",
    text: "生产工单",
    type: "select",
  },
  {
    value: "mcode",
    text: "产品编码",
    type: "select",
  },
  {
    value: "mname",
    text: "产品名称",
    type: "select",
  },
  {
    value: "remark",
    text: "备注",
    type: "string",
  },
];

export default {
  name: "MesHrMonthlyEmpDeclareList",
  mixins: [JeecgListMixin],
  components: {
    JSuperQuery,
    FxCompontensModal,
    MesHrMonthlyEmpDeclareModal,
  },
  data() {
    return {
      moment,
      approveStatus:{},
      fieldList: superQueryFieldList,
      superQueryFlag: false,
      superQueryParams: "",
      description: "月度人员名额申报管理页面",
      EnhanceJS: "",
      queryParam: {},
      cgButtonLinkList: [],
      cgButtonList: [],
      title: "", //存表名
      groupTag: [],
      queryInfo: [],
      code: "",
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义
      defColumns: [
        {
          title: "序号",
          dataIndex: "",
          key: "rowIndex",
          width: 50,
          align: "center",
          fixed: 'left',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: "单据编号",
          align: "center",
          dataIndex: "orderNo",
          scopedSlots: { customRender: "orderNo" },
        },
        {
          title: "申报日期",
          align: "center",
          dataIndex: "declareDate",
          width: 100,
          customRender: function (text) {
            return moment(text).format('YYYY-MM-DD')
          },
        },
        {
          title: "申报车间",
          align: "center",
          dataIndex: "declareWorkroom",
        },
        {
          title: "审批状态",
          align: "center",
          width: 80,
          dataIndex: "approveStatus",
           scopedSlots: { customRender: "approveStatus" },
        },
        {
          title: "班次",
          align: "center",
          dataIndex: "shiftName",
        },
        {
          title: "班组",
          align: "center",
          dataIndex: "declareClassname",
        },
        {
          title: "线体",
          align: "center",
          dataIndex: "linename",
        },
        {
          title: "生产工单",
          align: "center",
          dataIndex: "productionNo",
        },
        {
          title: "产品编码",
          align: "center",
          dataIndex: "mcode",
        },
        {
          title: "产品名称",
          align: "center",
          dataIndex: "mname",
        },
        {
          title: "备注",
          align: "center",
          dataIndex: "remark",
        },

        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          fixed: 'right',
          width: 80,
          scopedSlots: { customRender: "action" },
        },
      ],
      url: {
        list: "/mes-manpower/mesHrSpecialEmpManhourDeclare/list",
        delete:'/mes-manpower/mesHrSpecialEmpManhourDeclare/',//删除
        submit:'/mes-manpower/mesHrSpecialEmpManhourDeclare/submit/'//提交
      },
      dictOptions: {
        approveStatus: [],
      },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "50"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      selectedMainId: "",
    };
  },
  computed: {
    importExcelUrl: function () {
      return `${api.test}${this.url.importExcelUrl}`;
    },
    getWidth: function () {
      if (this.defColumns.length > 14) {
        return { width: "500px" };
      }
    },
    newSelectedMainId: function () {
      if (typeof this.selectedMainId == "number") {
        return this.selectedMainId.toString();
      } else {
        return this.selectedMainId;
      }
    },
  },

  created() {
    this.initColumns();
    this.setdefColumns();
    this.getControl("mes_hr_monthly_approve_status")
  },

  methods: {
    reloadData(){
      this.queryParam.orderNo=''
      this.loadData()
    },
    handleADDApply(){
      this.$refs.modalForm.visible=true,
      this.$refs.modalForm.dataList={}
      this.$refs.modalForm.dataList.change=false
      this.$refs.modalForm.title='特殊人员工时申报'
    },
    //确定按钮
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
    },
    //取消按钮
    handleReset(clearFilters) {
      clearFilters();
      this.searchText = "";
    },
    
    getControl(dic) {
      const dataItem = [];
      initDictOptions(dic).then((res) => {
      let obj={}
        res.data.forEach((item) => {
          dataItem.push({ text: item.text, value: item.value });
          obj[item.value]=item.text
        });
      this.approveStatus=obj
      });
      console.log(this.approveStatus)
      return dataItem;
    },

    setdefColumns() {
      if (this.columns.length > 13) {
        let arrLength = this.columns.length - 1;
        this.columns.forEach((item, index) => {
          item["width"] = 130;
        });
        this.columns[arrLength]["fixed"] = "right";
        this.columns[0]["fixed"] = "left";
        this.columns[1]["fixed"] = "left";
      }
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        });
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      }
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },
    //高级查询方法
    handleSuperQuery(arg) {
      if (!arg) {
        this.superQueryParams = "";
        this.superQueryFlag = false;
      } else {
        this.superQueryFlag = true;
        this.superQueryParams = JSON.stringify(arg);
      }
      this.loadData();
    },
    // 获取查询条件
    getQueryParams() {
      let sqp = {};
      if (this.superQueryParams) {
        sqp["superQueryParams"] = encodeURI(this.superQueryParams);
      }
      var param = Object.assign(sqp, this.queryParam,this.isorter);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.limit = this.ipagination.pageSize;
      return filterObj(param);
    },
    shwoModeal(res){
      this.$refs.modalForm.visible=true
      this.$refs.modalForm.dataList=res
      this.$refs.modalForm.dataList.change=true
    },

    handleEdit(res){
      if(res.approveStatus==0||res.approveStatus==2){
        this.$refs.modalForm.visible=true
        this.$refs.modalForm.dataList=res
        this.$refs.modalForm.dataList.change=false
      }else{
        this.$message.error('暂不可修改')
      }
    },
    handleDeleteItem(data){
      if(data.approveStatus==0){
        deleteAction(this.url.delete+'/'+data.id).then(res=>{
        if(res.code==0){
          this.$message.success('删除成功')
          this.loadData()
        }else{
          this.$message.error(res.msg)
        }
      })
      }else{
        this.$message.error('该单据不可删除')
      }
      
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
      this.selectedMainId = "";
    },
    submitButton(){
      getAction(this.url.submit+this.selectedMainId.toString()).then(res=>{
        if(res.code==0){
          this.$message.success('提交成功')
          this.loadData()
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedMainId = selectedRowKeys;
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!");
        return;
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      this.onClearSelected();
      var params = this.getQueryParams(); //查询条件
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.data.records;
          this.ipagination.total = res.data.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.loading = false;
      });
    },

    // 弹出窗组件
    showDemoModal() {
      this.$refs.modalCompon.modalShow();
    },

    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.approveStatus !== '0'
        }
      }
    }
  },
};
</script>
<style scoped>
@import "~@assets/less/common.less";
</style>